//
//  NoteViewController.m
//  Exam11-3
//
//  Created by 孙晓晔 on 2017/4/16.
//  Copyright © 2017年 孙晓晔. All rights reserved.
//

#import "NoteViewController.h"
#import <CoreData/CoreData.h>
#import "AppDelegate.h"

#import "NoteAddController.h"
#import "NoteEditController.h"
#import "NoteViewCell.h"

@interface NoteViewController ()<NoteAddControllerDelegate, NoteEditControllerDelegate>
@property(nonatomic,strong) NSMutableArray *noteArr; // 数据

@property(nonatomic,strong) AppDelegate *appDelegate;
@property(nonatomic,strong) NSManagedObjectContext *context;
@end

@implementation NoteViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    [self setUp];
    
}


// 懒加载
-(NSMutableArray *)noteArr {
    if (_noteArr == nil) {
        
        NSArray *arr = [self loadData];
        
        _noteArr = [NSMutableArray arrayWithArray:arr];
    }
    
    return _noteArr;
}

-(NSArray*) loadData {
    
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"NoteEntity"];
    
    //创建排序描述器 : 按创建时间属性列(Entity设计时添加此列@"createTime"(date类型))进行增序排序
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"createTime" ascending:NO];
    
    //设置查找请求的排序描述器
    [request setSortDescriptors:[NSArray arrayWithObject:sort]];
    
    NSError *error = nil;
    
    NSArray *arr = [_context executeFetchRequest:request error:&error];
    if (error) {
        NSLog(@"error");
    }
    
    return arr;
}

// 创建表结构
-(void)setUp {
    
    self.appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    
    NSPersistentContainer *container = self.appDelegate.persistentContainer;
    
    self.context = container.viewContext;
    
    // 打印目录
    NSArray *arr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    NSString *strDoc = [arr firstObject];
    
    NSLog(strDoc, nil);
}

#pragma mark - NoteAddControllerDelegate
// 新增信息
- (void)addNote:(NoteAddController *)addController note:(Note *)note {
    
    NSManagedObject *row = [NSEntityDescription insertNewObjectForEntityForName:@"NoteEntity" inManagedObjectContext:self.context];
    
    [row setValue:note.content forKey:@"content"];
    [row setValue:note.createTime forKey:@"createTime"];
    
    [self.appDelegate saveContext];
    
    self.noteArr = nil;
    
    // 刷新表视图
    [self.tableView reloadData];
}

#pragma mark - NoteEditControllerDelegate
// 编辑信息
- (void)editNote:(NoteEditController *)editController note:(Note *)note {
    
    [self.appDelegate saveContext];
    
    [self.tableView reloadData];
}

#pragma mark - Table view data source

// 设置行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 60;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.noteArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *identifier = @"notecell";
    
    NoteViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"NoteViewCell" owner:nil options:nil] firstObject];
        
        cell.model = self.noteArr[indexPath.row];
    }
    
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    return cell;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        Note *note = self.noteArr[indexPath.row];
        
        [self deleteNote:note];
        
        [self.noteArr removeObjectAtIndex:indexPath.row];
        
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}

// 删除数据
-(void)deleteNote:(Note*)note {
    
    NSManagedObject *deleteObject = (NSManagedObject*)note;
    
    [self.context deleteObject:deleteObject];
    
    [self.appDelegate saveContext];
}

/**
 *  修改Delete按钮文字为“删除”
 */
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return @"删除";
}

- (IBAction)edit:(UIBarButtonItem *)sender {
    
    if ([sender.title isEqual: @"编辑"]) {
        sender.title = @"确定";
        [self.tableView setEditing:YES animated:YES];
    } else {
        sender.title = @"编辑";
        [self.tableView setEditing:NO animated:YES];
    }
    
}


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [self performSegueWithIdentifier:@"note2edit" sender:nil];
}

#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    
    NSString *str = segue.identifier;
    
    if ([str isEqualToString:@"note2add"]) {
        NoteAddController *add = segue.destinationViewController;
        add.delegate = self;
    } else if ([str isEqualToString:@"note2edit"]) {
        NoteEditController *edit = segue.destinationViewController;
        
        NSIndexPath *path = [self.tableView indexPathForSelectedRow];
        
        edit.delegate = self;
        edit.note = self.noteArr[path.row];
    }
}

@end
